import { createRouter, createWebHistory } from 'vue-router'
import store from '../store/index'

const routes = [
  {
    path: '/',
    redirect: '/home/index'
  }, {
    path: '/register',
    component: () => import(/* webpackChunkName: "register" */ '../pages/Register.vue')

  }, {
    path: '/login',
    component: () => import(/* webpackChunkName: "login" */ '../pages/Login.vue')
  }, {
    path: '/home',
    name:"home",
    component: () => import(/* webpackChunkName: "home" */ '../pages/Home.vue'),
    beforeEnter(to,from){
      // 通过token获取用户信息，存放到vuex
      store.dispatch('user/loadUser');
    },
    children: [{
      // 主页的首页部分
      path: 'index',
      name:"index",
      component: () => import(/* webpackChunkName: "home_index" */ '../pages/home/Index.vue'),
    },{
      // 订单列表  ——中间那个订单
      path: 'orders',
      name: 'orders',
      component: () => import(/* webpackChunkName: "home_orders" */ '../pages/home/Orders.vue'),
    },
    {
      // 订单详情 ——中间那个订单
      path: 'details',
      name: 'details',
      component: () => import(/* webpackChunkName: "home_orders" */ '../pages/home/orders/Details'),
    },{
        path:"address",
        name:"address",
        component: () => import ('../pages/home/address/List.vue'),
    }
    ,{
      //订单确认页面——支付页面
      path: 'confirm_order',
      name:'confirm_order',
      component: () => import(/* webpackChunkName: "home_orders" */ '../pages/home/orders/Confirm.vue'),
    },{
      path: 'me',
      component: () => import(/* webpackChunkName: "home_me" */ '../pages/home/Me.vue'),
    },

  ]
  },
  {
    path:"/address_details",
    name:"address_details",
    component:()=>import("../pages/home/address/Details.vue")
  },
  {
    path:"/address",
    name:"address",
    component: () => import ('../pages/home/address/List.vue'),
  },
]

const router = createRouter({
  // 设置一个目录，为history打包做准备
  base:'/estoreApp/',
  // hash模式打包锚点不可用
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to,from,next)=>{
  // 白名单
  let paths = ["/login","/register"]
  if(paths.indexOf(to.path)!=-1){
    next();
  }
  // 验证token
  let token = localStorage.getItem('token');
  if(!token){
    next('/login')
  } else {
    next();
  }
})

export default router
